<?php

namespace App\Http\Middleware;

use App\Exceptions\ValidationException;
use App\Helpers\ResponseEnum;
use Closure;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Illuminate\Http\Request;

/**
 * 用于验证api用户的登录
 */
class checkLogin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        $token = $request->header('authorization');
        if(!isset($token) || empty($token)){
            throw new ValidationException(ResponseEnum::HTTP_ERROR,'请先登录');
        }
        $token = explode(' ',$token)[1];
        //echo $token;
        //echo config('jwt.key');
        try {
            JWT::$leeway = 60;//当前时间减去60，把时间留点余地
            $decoded = JWT::decode($token, new Key(config('jwt.key'), 'HS256')); //HS256方式，这里要和签发的时候对应
            $decoded_array = (array)$decoded;
            $request->u_id =$decoded_array['data']->userid;
            return $next($request);
        } catch(\Firebase\JWT\SignatureInvalidException $e) {  //签名不正确
            throw new ValidationException(ResponseEnum::HTTP_ERROR,'签名不正确');
        }catch(\Firebase\JWT\BeforeValidException $e) {  // 签名在某个时间点之后才能用
            throw new ValidationException(ResponseEnum::HTTP_ERROR,'token不正确');
        }catch(\Firebase\JWT\ExpiredException $e) {  // token过期
            throw new ValidationException(ResponseEnum::TOKEN_ERROR,'token过期');
        }catch(Exception $e) {  //其他错误
            throw new ValidationException(ResponseEnum::HTTP_ERROR,'非法请求'.$e->getMessage());
        }catch(\UnexpectedValueException $e) {  //其他错误
            throw new ValidationException(ResponseEnum::HTTP_ERROR,'非法请求'.$e->getMessage());
        } catch(\DomainException $e) {  //其他错误
            throw new ValidationException(ResponseEnum::HTTP_ERROR,'非法请求'.$e->getMessage());
        }

    }
}
